<?php
namespace app\know\controller;

use app\know\controller\AdminKnowBaseController;
use app\know\validate\NewWordExampleValidate;
use app\know\validate\SentenceValidate;
use app\know\model\MaterialModel;
use app\know\model\SentenceModel;
use think\facade\Db;
use think\facade\Log;

/**
 * Class AdminNewWordController 佳句积累控制器
 * @package app\know\controller
 */
class AdminSentenceController extends AdminKnowBaseController
{
    /**
     * 佳句积累
     * @adminMenu(
     *     'name'   => '佳句积累',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 34000,
     *     'icon'   => '',
     *     'remark' => '佳句积累',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_sentence_index_view');

        if (!empty($content)) 
		{
            return $content;
        }

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();

		$this->assign('materials', $materials);
        return $this->fetch();
    }

    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.is_delete' => 0 ];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }
        if ($material_uuid)
        {
            $where['a.material_uuid'] = $material_uuid;
        }
        $model = new SentenceModel();

        $count = $model->where($where)->alias('a')->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_material c', 'a.material_uuid = c.uuid')
                    ->leftJoin('cmf_know_chapter d', 'a.chapter_uuid = d.uuid and a.material_uuid = d.relate_uuid')
                    ->page($pageNumber, $pageSize)
                    ->field('a.*, c.name as teaching_name, d.name as chapter_name')
                    ->select();
        
        foreach ($rows as $v)
        {
            $v['analysis'] = htmlspecialchars_decode(htmlspecialchars_decode($v['analysis']));  
        }
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];
        
        try 
		{
			$model = new SentenceModel();
			$param['uuid'] = $model->getUUID();
            $this->validateFailError($param, 'Sentence.add');

            $row = SentenceModel::create($param);
            if (empty($row)) 
            {
                throw new Exception('佳句添加失败');
            }
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $this->opLog([
            'table_name' => $model->getTableName(),
            'sql' => SentenceModel::getLastSql(),
            'create_user' => $user['user_login'],
        ]);
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $this->validateFailError($param, 'NewWord.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
		{
            SentenceModel::where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => (new SentenceModel())->getTableName(),
                'sql' => SentenceModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
		{
            $user = $this->getAdminUser();
            $param['modify_user'] = $user['user_login'];
            $param['modify_datetime'] = date("Y-m-d H:i:s");
        
            $this->validateFailError($param, 'Sentence.edit');
            $d = SentenceModel::where('id', $id)->find();
            SentenceModel::where('id', $id)->save($param);

            $this->opLog([
                'table_name' => (new SentenceModel())->getTableName(),
                'sql' => SentenceModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }
        $this->success('修改成功');
    }

    public function maxOrder()
    {
        $order = SentenceModel::max('order_number');
        $this->success('', '', $order);
    }

    public function getItem()
    {
        $id = $this->request->param('id', '');

        $where = ['is_delete' => 0, 'id' => $id];
        $model = new SentenceModel();
        $row = $model->where($where)->find();

        $this->success('', null, $row);
    }

}
